package com.gxuwz.prrs.service.impl;

import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.reflect.TypeToken;
import com.gxuwz.prrs.bean.*;
import com.gxuwz.prrs.constant.HttpCodeConstants;
import com.gxuwz.prrs.service.BaseService;
import com.gxuwz.prrs.utils.BaseApplication;
import com.gxuwz.prrs.utils.RequestUtils;
import okhttp3.FormBody;

import java.lang.reflect.Type;

/**
 * @author 张钧
 * @Description
 * @create 2023-05-24 上午 11:22
 */
public class AuthServiceImpl implements BaseService<UserInfo,Page<UserInfo>> {

	public boolean login(LoginForm loginForm){
		FormBody.Builder builder = new FormBody.Builder();
		builder.add("account", loginForm.getStudentNumber());
		builder.add("password",loginForm.getPassword());
		String url = "/auth/login";
		Type type = new TypeToken<CommonResponse<String>>() {
		}.getType();
		CommonResponse<String> s = RequestUtils.postRequest(url,builder.build(),type);
		if(s != null){
			String token = s.getData();
			SharedPreferences sharedPreferences = BaseApplication.getContext().getSharedPreferences("token", Context.MODE_PRIVATE);
			SharedPreferences.Editor edit = sharedPreferences.edit();
			edit.putString("token",token);
			edit.apply();
			return HttpCodeConstants.SUCCESS.equals(s.getCode());
		}
		return false;
	}

	public boolean changePassword(ChangePasswordForm changePasswordForm){
		FormBody.Builder builder = new FormBody.Builder();
		builder.add("oldPassword",changePasswordForm.getOldPassword());
		builder.add("newPassword",changePasswordForm.getNewPassword());
		String url = "/auth/change/password";
		Type type = new TypeToken<CommonResponse<Boolean>>() {
		}.getType();
		CommonResponse<Boolean> s = RequestUtils.postRequest(url,builder.build(),type);
		if(s != null && HttpCodeConstants.SUCCESS.equals(s.getCode())){
			return s.getData();
		}
		return false;
	}

	public UserInfo getUserInfo(){
		String url = "/user/info";
		Type type = new TypeToken<CommonResponse<UserInfo>>() {
		}.getType();
		CommonResponse<UserInfo> s =  RequestUtils.getRequest(url,type);
		if(s != null){
			return s.getData();
		}else {
			return null;
		}
	}

	@Override
	public Page<UserInfo> page(Page<UserInfo> page) {
		return null;
	}
}
